﻿
using AutoMapper;
using BBICMS.Data.Repositories.Identity;
using BBICMS.Model.Security;
using BBICMS.DTO;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;


namespace BBICMS.Repository
{
    public class MenuRepository : GenericRepository<Menu>, IMenuRepository
    {
        public MenuRepository(DbContext context) : base(context) { }


        public List<Menu> CurrenMenuCrumbs(string area, string controller, string action)
        {
                     
            List<Menu> menus = new List<Menu>();            
            Menu vMenu = this.GetFilteredElements((m => m.Area == area && m.Controller == controller && m.Action == action)).FirstOrDefault();

            if (vMenu != null)
                RecursiveLoad(vMenu, menus);        

            return menus;

        }

        /// <summary>
        /// 递归获取父项
        /// </summary>
        /// <param name="vMenu"></param>
        /// <param name="Parents"></param>
        private void RecursiveLoad(Menu vMenu, List<Menu> Parents)
        {
            Parents.Insert(0, vMenu);
            if (vMenu.ParentMenu != null)
            {
                RecursiveLoad(vMenu.ParentMenu, Parents);
            }
        }


        public IEnumerable<MenuDTO> GetMenusByCategoryId(int categoryId)
        {
            var orgMenus = this.GetFilteredElements((m => m.CategoryId == categoryId && m.ParentId == null), (m => m.ChildMenus));

      
            IEnumerable<MenuDTO> menus = Mapper.Map<IEnumerable<MenuDTO>>(orgMenus);
              
            return menus;
        }

        public IEnumerable<MenuDTO> GetFlatMenusByCategoryId(int categoryId)
        {
            var orgMenus = this.FindBy((m => m.CategoryId == categoryId));

         
            IEnumerable<MenuDTO> menus = Mapper.Map<IEnumerable<MenuDTO>>(orgMenus);

            return menus;
        }

    }
}
